﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Tool.Helper
{
    public class ConfigHelper
    {
        /// <summary>
        /// 获取Value
        /// </summary>
        /// <param name="key"></param>
        /// <returns>Key不存在返回null</returns>
        public static  string Get(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
  
        public static T Get<T>() where T:new ()
        {
            var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var appSettings = configuration.AppSettings.Settings;
            var result = new T();
            foreach (var setting in appSettings)
            {
                KeyValueConfigurationElement de = (KeyValueConfigurationElement)setting;
                var property = result.GetType().GetProperty(de.Key);
                if (property != null)
                {
                    var type = property.PropertyType;
                    var data = JsonConvert.DeserializeObject(de.Value, type);
                    property.SetValue(result, data);
                }
            }
            return result;
        }
    }
}
